package com.djx.commons.config.shiro;

import com.djx.business.access.service.PermissionService;
import com.djx.business.access.service.UserService;
import com.djx.commons.response.ProfileResult;

import com.djx.entity.access.Permission;
import com.djx.entity.access.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Set;

@Slf4j
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private PermissionService permissionService;

    @Autowired
    private UserService userService;

    /**
     * 授权
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        // TODO 加上redis之后无法强转
        ProfileResult result = (ProfileResult) principals.getPrimaryPrincipal();

        log.info("当前用户的权限为 ：： ：  {}", result);
        Set<String> apis = (Set<String>) result.getRoles().get("apis");
        //设置构造授权对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(apis);
        return info;
    }

    /**
     * 登录认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();
        String password = new String(usernamePasswordToken.getPassword());

        //根据用户名和密码去后台查询用户
        User user = userService.findByUsernameAndPassword(username, password);

        if (user != null) { // 用户存在

            if (user.getUserStatus().equals("1")) { //该账号禁用
                return null;
            }
            //如果该用户不被禁用  构造安全数据
            ProfileResult profileResult = null;
            if (user.getUserLevel().equals("user")) {
                profileResult = new ProfileResult(user);
            } else if (user.getUserLevel().equals("admin")) {
                List<Permission> permissions = permissionService.permissions();
                profileResult = new ProfileResult(user, permissions);
            }
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(profileResult, user.getPassword(), this.getName());
            System.out.println("this.getName():: " + this.getName());
            return info;
        } else { //用户不存在
            return null;
        }
    }
}
